package main

import (
	"errorHanding/filelistingserver/filelisting"
	"github.com/gpmgo/gopm/modules/log"
	"net/http"
	_ "net/http/pprof"
	"os"
)

type appHandler func(writer http.ResponseWriter, request *http.Request) error

func errWrapper(handler appHandler) func(w http.ResponseWriter, r *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			r := recover()
			if r != nil {
				log.Warn("%v", r)
				http.Error(w, http.StatusText(http.StatusInternalServerError),
					http.StatusInternalServerError)
			}
		}()
		err := handler(w, r)
		if err != nil {
			if userErr, ok := err.(userErr); ok {
				http.Error(w, userErr.Message(), http.StatusBadRequest)
				return
			}
			code := http.StatusOK
			log.Warn("error handing request: %s", err.Error())
			switch {
			case os.IsNotExist(err):
				//http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
				code = http.StatusNotFound
			case os.IsPermission(err):
				code = http.StatusForbidden
			default:
				code = http.StatusInternalServerError
			}
			http.Error(w, http.StatusText(code), code)
		}
	}
}

type userErr interface {
	error
	Message() string
}

func main() {
	//使用了函数式编程做参数
	http.HandleFunc("/", errWrapper(filelisting.HandlerFileList))

	err := http.ListenAndServe(":8888", nil)

	if err != nil {
		panic(err)
	}
}
